<?php
namespace app\api\model;

use Elasticsearch\ClientBuilder;


class Esapi
{
    private $client;

    public function __construct()
    {
        $params['hosts'] =  '127.0.0.1:9200';
        vendor('autoload');//引入文件
        $this->client = ClientBuilder::create()->setHosts($params)->build();
    }

    /*
     * 创建索引
     *
     * 成功返回
     * array(2) {["acknowledged"]=>bool(true),["shards_acknowledged"]=>bool(true)}
     * 报错返回
     * array(2) {["error"]=>array(5) {},["status"]=>int(400)}
     *
     * */
    public function create_index($index_name) {
        $params = [
            'index' => $index_name,
            'body' => [
                'settings' => [
                    'number_of_shards' => 5,
                    'number_of_replicas' => 0
                ]
            ]
        ];

        try {
            return $this->client->indices()->create($params);
        } catch (\Elasticsearch\Common\Exceptions\BadRequest400Exception $e) {
            $msg = $e->getMessage();
            $msg = json_decode($msg,true);
            return $msg;
        }
    }

    // 删除索引
    public function delete_index($index_name) {
        $params = ['index' => $index_name];
        $response = $this->client->indices()->delete($params);
        return $response;
    }

    // 创建文档模板
    public function create_mappings($index_name,$properties) {
        $type_name = $index_name."_type";
        $params = [
            'index' => $index_name,
            'type' => $type_name,
            'body' => [
                $type_name => [
                    '_source' => [
                        'enabled' => true
                    ],
                    'properties' => $properties
                ]
            ]
        ];

        $response = $this->client->indices()->putMapping($params);
        return $response;
    }

    // 查看映射
    public function get_mapping($index_name) {
        $type_name = $index_name."_type";
        $params = [
            'index' => $index_name,
            'type' => $type_name
        ];
        $response = $this->client->indices()->getMapping($params);
        return $response;
    }

    // 添加文档
    public function add_doc($id,$doc,$index_name) {
        $type_name = $index_name."_type";
        $params = [
            'index' => $index_name,
            'type' => $type_name,
            'id' => $id,
            'body' => $doc
        ];

        $response = $this->client->index($params);
        return $response;
    }

    // 判断文档存在   返回布尔值
    public function exists_doc($id,$index_name) {
        $type_name = $index_name."_type";
        $params = [
            'index' => $index_name,
            'type' => $type_name,
            'id' => $id
        ];
        $response = $this->client->exists($params);
        return $response;
    }

    // 获取文档
    public function get_doc($id = 1,$index_name = 'test_ik',$type_name = 'users') {
        $params = [
            'index' => $index_name,
            'type' => $type_name,
            'id' => $id
        ];

        $response = $this->client->get($params);
        return $response;
    }

    // 更新文档
    public function update_doc($id,$doc,$index_name) {
        $type_name = $index_name."_type";
        // 可以灵活添加新字段,最好不要乱添加
        $params = [
            'index' => $index_name,
            'type' => $type_name,
            'id' => $id,
            'body' => ['doc'=>$doc]
        ];

        $response = $this->client->update($params);
        return $response;
    }

    // 删除文档
    public function delete_doc($id = 1,$index_name = 'test_ik',$type_name = 'users') {
        $params = [
            'index' => $index_name,
            'type' => $type_name,
            'id' => $id
        ];

        $response = $this->client->delete($params);
        return $response;
    }

    // 查询文档 (分页，排序，权重，过滤)
    public function search_doc($index_name,$match_arr,$highlightArr,$from = 0,$size = 100) {
        $type_name = $index_name."_type";
        $params = [
            'index' => $index_name,
            'type' => $type_name,
            'from' => $from,
            'size' => $size,
            'body' => [
                'query' => [
                    'bool' => [
                        'should' => $match_arr,
                    ],
                ],
                'highlight' => [
                    'pre_tags' => ["<span class='hightlight'>"],
                    'post_tags' => ["</span>"],
                    'fields' => $highlightArr
                ]
            ]
        ];

        $results = $this->client->search($params);
        return $results;
    }

    // 多条件查询文档 (分页，排序，权重，过滤)
    public function multi_param_search_doc($index_name,$match_arr,$sort_arr,$include_fields=[],$highlightArr=[],$from = 0,$size = 0) {
        $type_name = $index_name."_type";
        $sort_arr['_score'] = ['order'=>'desc'];
        $params = [
            'index' => $index_name,
            'type' => $type_name,
            'body' => [
                'query' => $match_arr,
                'sort'  => [$sort_arr],
//                'highlight' => [
//                    'pre_tags' => ["<span class='hightlight'>"],
//                    'post_tags' => ["</span>"],
//                    'fields' => $highlightArr
//                ]
            ]
        ];
        if(!empty($include_fields)){
            $params['body']['_source']['includes'] = $include_fields;
        }
        if(!empty($from)){
            $params['from'] = $from;
        }
        if(!empty($size)){
            $params['size'] = $size;
        }
        $results = $this->client->search($params);
        return $results;
    }

    //判断索引是否存在
    public function getIndex($index_name)
    {
        $params['index'] = $index_name;
        $results = $this->client->indices()->exists($params);
        return $results;
    }


}